/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dale2507.gates.misc;

import dale2507.gates.GatePlugin;
import dale2507.gates.Messenger;
import dale2507.gates.exceptions.GateBuilderException;
import dale2507.gates.exceptions.PermissionException;
import dale2507.gates.exceptions.VerificationException;
import dale2507.gates.gate.Display;
import dale2507.gates.gate.GateBuilder;
import org.bukkit.Bukkit;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;

/**
 *
 * @author Dale
 */
public class SignGateCreator implements Listener {
    
    /**
     * Handles the placing of a sign. Attempts to create a gate if the sign is a valid gate sign.
     * @param event Sign change event
     */
    @EventHandler(priority = EventPriority.LOW)
    public void onSignChange(SignChangeEvent event) {
        if (event.getLine(0).equalsIgnoreCase("[Gate]")) {
            final Block block = event.getBlock();
            final Player player = event.getPlayer();
            
            Bukkit.getScheduler().scheduleSyncDelayedTask(GatePlugin.getInstance(), new Runnable() {
                @Override
                public void run() {
                    try {
                        createGateFromSign(player, block);
                        Messenger.sendMessage(player, Messenger.SUCCESS, "Gate created");
                    } catch (GateBuilderException | VerificationException | PermissionException ex) {
                        Messenger.sendMessage(player, Messenger.ERROR, "Could not build gate: " + ex.getMessage());
                    }
                }
            });
        }
    }

    /**
     * Attempts to create a gate from a sign
     * @param p Player that placed the sign
     * @param block Block where the sign was placed
     * @throws VerificationException Thrown if an error occurs creating the gate components
     * @throws GateBuilderException Thrown if an error occurs building the gate
     */
    public void createGateFromSign(Player p, Block block) throws VerificationException, GateBuilderException, PermissionException {
            new GateBuilder().setDisplay(new Display(block))
                    .findRing(block)
                    .findDHD(block)
                    .build(p);
    }
    
}
